package com.changhong.framework.sdfs.namenode.server.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 属性工具类操作properties
 * @author summer
 */
public class PropertyUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
    private static Properties props;
    private static volatile PropertyUtil propertyUtil;
    private static final Object LOCK =new Object();
    private static final String[] DEFAULT_FILE_SEARCH_LOCATIONS = new String[]{"./config/", "./"};

    private PropertyUtil(String loadFile){
        loadProps(loadFile);
    }

    public static PropertyUtil getInstance(String loadFile){
        if(propertyUtil==null){
            synchronized (LOCK){
                propertyUtil=new PropertyUtil(loadFile);
                return propertyUtil;
            }
        }
        return propertyUtil;
    }

    private static synchronized void loadProps(String loadFile){
        logger.info("开始加载properties文件内容.......");
        props = new Properties();
        InputStream in = null;
        try {
            if(loadFile == null) {
                assert false;
                if ("".equals(loadFile)) {
                    throw new RuntimeException("文件为空。");
                }
            }
            in = PropertyUtil.class.getClassLoader().getResourceAsStream(loadFile);
            props.load(in);
        } catch (FileNotFoundException e) {
            logger.error("jdbc.properties文件未找到");
        } catch (IOException e) {
            logger.error("出现IOException");
        } finally {
            try {
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("jdbc.properties文件流关闭出现异常");
            }
        }
        logger.info("加载properties文件内容完成...........");
        logger.info("properties文件内容：" + props);
    }

    public Properties getProps(){
        return props;
    }
}
